import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '@/views/Dashboard.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      hideInMenu: true,
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: {
      title: '注册',
      hideInMenu: true,
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/GlobalLayout.vue'),
    redirect: '/dashboard',
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '仪表盘',
          icon: 'Monitor',
          requiresAuth: true
        }
      },
      {
        path: '/realtime',
        name: 'Realtime',
        component: () => import('@/views/Realtime.vue'),
        meta: {
          title: '实时监控',
          icon: 'View',
          requiresAuth: true,
          permission: 'view'
        }
      },
      {
        path: '/history',
        name: 'History',
        component: () => import('@/views/History.vue'),
        meta: {
          title: '历史数据',
          icon: 'Clock',
          requiresAuth: true,
          permission: 'view'
        }
      },
      {
        path: '/settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: {
          title: '系统设置',
          icon: 'Setting',
          requiresAuth: true,
          permission: 'manage_user'
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: {
      title: '页面不存在',
      hideInMenu: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 气象站数据管理系统`
  } else {
    document.title = '气象站数据管理系统'
  }
  
  console.log(`路由导航: ${from.path} -> ${to.path}`)
  
  // 如果是登录页或注册页，且已登录，则重定向到首页
  if ((to.name === 'Login' || to.name === 'Register') && localStorage.getItem('token')) {
    console.log('已登录用户尝试访问登录/注册页，重定向到首页')
    next({ path: '/' })
    return
  }
  
  // 如果是登录页或注册页，直接通过
  if (to.name === 'Login' || to.name === 'Register') {
    console.log('允许访问登录/注册页')
    next()
    return
  }
  
  // 检查是否需要登录
  const token = localStorage.getItem('token')
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)
  
  if (requiresAuth && !token) {
    console.log('需要登录，重定向到登录页')
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }
  
  // 检查用户角色
  const roleCode = localStorage.getItem('roleCode')
  console.log('当前用户角色:', roleCode)
  
  // 如果是被禁用的用户，只能访问登录页
  if (roleCode === 'baned_user') {
    console.log('被禁用的用户，重定向到登录页')
    next({ name: 'Login' })
    return
  }
  
  // 检查页面是否需要特定权限
  const requiredPermission = to.meta.permission
  
  if (requiredPermission) {
    console.log(`页面需要权限: ${requiredPermission}`)
    // 管理员拥有所有权限
    if (roleCode === 'admin') {
      console.log('管理员权限，允许访问')
      next()
      return
    }
    
    // 对于普通用户，只允许访问带有 'view' 权限的页面
    if (roleCode === 'normal_user' && requiredPermission === 'view') {
      console.log('普通用户有查看权限，允许访问')
      next()
      return
    }
    
    // 如果没有所需权限，重定向到仪表盘
    console.log('没有所需权限，重定向到仪表盘')
    next({ name: 'Dashboard' })
    return
  }
  
  console.log('导航通过')
  next()
})

export default router